<template>
  <div>
    <page-main class="searchMain">
      <div class="searchBox">
        <span>搜索</span>
        <el-input
          v-model="searchValue"
          class="search"
          @keyup.enter="searchInputList"
          placeholder="请输入ID 单位名称或者监管等级"
        ></el-input>
      </div>
    </page-main>
    <page-main>
      <el-table
        :data="tableData.filter((data) => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
        :default-sort="{ prop: 'id', order: 'ascending' }"
      >
        <!-- <el-table-column label="社会单位名称" prop="unit_name"></el-table-column> -->
        <el-table-column label="用户名" prop="username"> </el-table-column>
        <el-table-column label="姓名" prop="name"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="手机号" prop="phone"> </el-table-column>
        <el-table-column label="区域" prop="region_name"> </el-table-column>
        <el-table-column label="所属单位" prop="unit_name"> </el-table-column>
        <el-table-column label="查看详情">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="lookDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #header>
            <el-button size="mini" type="primary" @click="dialogFormVisible = true">添加</el-button>
          </template>
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :total="total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
      <!-- <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          layout="prev, pager, next, jumper"
          :hide-on-single-page="true"
        >
        </el-pagination>
      </div> -->
    </page-main>
    <el-dialog
      v-model="dialogFormVisible"
      width="60%"
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form ref="childForm" :rules="rules" :model="formData" :disabled="disabled">
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择">
                <el-option v-for="item in userTypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="formData.username"
                :maxlength="18"
                oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="formData.password"
                show-password
                :maxlength="18"
                oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="角色Id" prop="role_id">
              <el-select v-model="formData.role_id" placeholder="请选择">
                <el-option v-for="item in roleList" :key="item.id" :label="item.role_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
                <!-- <el-radio label="3">保密</el-radio> -->
              </el-radio-group>
              <!-- <el-select v-model="formData.sex" placeholder="请选择">
                <el-option
                  v-for="item in sexLists"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="formData.phone" oninput="value=value.replace(/[^\d]/g,'')" :maxlength="11"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6" :offset="1">
            <el-form-item label="头像" prop="head_img">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                class="img"
                :before-remove="imgRemove"
                :on-change="imgChange"
                accept=".jpg,.png,.jpeg"
                :file-list="imgFileList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="身份证" prop="card_no"><el-input v-model="formData.card_no"></el-input></el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="formData.age" oninput="value=value.replace(/[^\d]/g,'')" :maxlength="2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="岗位" prop="job">
              <el-input v-model="formData.job"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="formData.qq"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="formData.status"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import storage from '@/util/storage'
import { ElMessage } from 'element-plus'
// 分页
import paginationMixin from '@/mixins/pagination'
export default {
  // 分页
  mixins: [paginationMixin],
  data() {
    return {
      searchValue: '',
      total: 0,
      disabled: false,
      dialogFormVisible: false,
      tableData: [],
      search: '',
      tableDataInfo: '',
      imgFileList: [],
      formData: {
        type: '',
        username: '',
        password: '',
        role_id: '',
        name: '',
        sex: '',
        phone: '',
        head_img: '',
        card_no: '',
        age: '',
        job: '',
        qq: '',
        user_type: '',
        status: ''
      },
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 6, max: 18, trigger: 'blur', message: '用户名长度为6到18位' }
        ],
        password: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 6, max: 18, trigger: 'blur', message: '密码长度为6到18位' }
        ],
        role_id: [{ required: true, message: '请选择', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 11, max: 11, trigger: 'blur', message: '请输入正确的手机号' }
        ],
        head_img: [{ required: true, message: '请上传', trigger: 'blur' }],
        card_no: [{ required: true, message: '请输入', trigger: 'blur' }],
        age: [{ required: true, message: '请输入', trigger: 'blur' }],
        job: [{ required: true, message: '请选择', trigger: 'blur' }],
        qq: [{ required: true, message: '请输入', trigger: 'blur' }],
        user_type: [{ required: true, message: '请选择', trigger: 'blur' }],
        status: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      id: '',
      unit_id: '', //单位id
      sexLists: [
        { name: '男', id: 1 },
        { name: '女', id: 2 },
        { name: '保密', id: 3 }
      ],
      typeList: [],
      roleList: [],
      userTypeList: [],
      upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
      upLoadImgData: {
        type: 'image'
      }
    }
  },
  created() {
    this.$api.get('/unit/Setting/userType').then((res) => {
      this.userTypeList = res.data
    })
    this.unit_id = this.$route.query.id
    this.getDataList()
    this.getRoleList()
  },
  computed: {
    upLoadImgHeader() {
      return {
        'A-Token': this.$store.state.user.a_token,
        'U-Token': this.$store.state.user.u_token
      }
    }
  },
  methods: {
    //   图片
    imgChange() {
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'none'
    },
    imgRemove() {
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'block'
    },
    // 获取角色列表
    getRoleList() {
      this.$api.get('/unit/XfRole/lists').then((res) => {
        this.roleList = res.data
      })
    },
    headImgUpSuccess(e) {
      this.formData.head_img = e.data.result
    },
    closeDialog() {
      this.$refs.childForm.resetFields()
      let temp = this.formData
      for (let key in temp) {
        temp[key] = ''
      }
      this.formData = temp
      this.id = ''
      this.disabled = false
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'block'
      this.imgFileList = []
    },
    colTitle(row, column, cellValue, index, e) {
      if (e == 'danger_source') {
        let temp = ['', '公众', '监管机构', '维保单位', '社会单位']
        return temp[cellValue]
      } else if (e == 'status') {
        let temp = ['', '未整改', '待审核', '已整改']
        return temp[cellValue]
      }
    },
    getDataList(page) {
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      let query = {
        rows: this.pagination.size,
        page: this.pagination.page,
        unit_id: this.unit_id,
        keywords: this.searchValue
      }
      this.$api.post('/unit/YjUser/Lists', query).then((res) => {
        this.tableData = res.data.list
        this.tableDataInfo = res.data
        this.total = res.data.total
      })
    },
    // 搜索
    searchInputList() {
      this.getDataList()
    },
    handleEdit(index, row) {
      this.id = row.id
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
      if (row.head_img) {
        this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
        setTimeout(() => {
          let img = document.getElementsByClassName('img')[0]
          img.children[1].style.display = 'none'
        }, 100)
      }
    },
    // 查看详情
    lookDetails(row) {
      this.disabled = true
      this.id = row.id
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true
      if (row.head_img) {
        this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
        setTimeout(() => {
          let img = document.getElementsByClassName('img')[0]
          img.children[1].style.display = 'none'
        }, 100)
      }
    },
    handleSizeChange(e) {},
    handleCurrentChange(e) {
      this.getDataList(e)
    },
    submitForm() {
      this.$refs.childForm.validate((valid) => {
        if (valid) {
          let data = this.formData
          data.unit_id = this.unit_id
          if (this.id) {
            data.id = this.id
          } else {
            data.id = 0
          }
          this.$api.post('/unit/YjUser/Save', data).then(() => {
            this.getDataList()
            this.dialogFormVisible = false
          })
        } else {
          ElMessage.error('请填写完整')
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.block {
  display: flex;
  justify-content: center;
}
.searchBox {
  display: flex;
  span {
    width: 50px;
    line-height: 40px;
    text-align: center;
  }
  .search {
    width: 30%;
  }
}
.searchMain {
  height: 80px;
}
</style>
